import base64
from flask import Flask, request
import pandas as pd 
from flask import Flask
from flask_cors import CORS
import json

import pymysql
from  Datas.dataClear import DataClear
from  Dao.jobs import Job

app = Flask(__name__) # 创建Flask应用程序实例

CORS(app, origins='http://localhost:5173')
CORS(app, origins='http://127.0.0.1:5173')

Data = DataClear()

conn =  pymysql.connect(  
            host='localhost',  # 数据库服务器地址，本地数据库使用'localhost'  
            user='root',  # 数据库用户名  
            password='wujianping123',  # 数据库密码  
            database='jobdata',  # 数据库名称  
            charset= 'utf8mb4'
        ) 


@app.route('/index',methods=['get']) # 装饰器将URL路径'/'映射到函数hello_world()
def hello_world():
    return 'Hello, World!'

@app.route('/jobs/pie',methods=['get'])
def pie():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        return {'code':200,'result':Data.pie()}

@app.route('/jobs/clound/name',methods=['get'])
def map():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        lis = Data.wordClound()
        result = [{
            'value':i[1],
            'name':i[0]
        } for i in lis]
        return {'code':200,'result':result}

@app.route('/jobs/clound/ltd',methods=['get'])
def map_p():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        lis = Data.wordClound_()
        result = [{
            'value':i[1],
            'name':i[0]
        } for i in lis]
        return {'code':200,'result':result}

@app.route('/jobs/line',methods=['get'])
def line():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        return {'code':200,'result':Data.line()}
    
@app.route('/jobs/maxmin',methods=['get'])
def line_max_min():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        return {'code':200,'result':Data.line_max_min()}

@app.route('/jobs/count',methods=['get'])
def job_count():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        return {'code':200,'result':Data.job_count()}

@app.route('/jobs/highsalary',methods=['get'])
def high_salary():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        return {'code':200,'result':Data.high_salary()}

@app.route('/jobs/links',methods=['get'])
def links():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        info_id = request.args.get('info_id')
        return Job().get_job(info_id)

@app.route('/jobs/all',methods=['get'])
def index():
    if request.method != 'GET':
        return {'code':200,'msg':'错误的请求方法'}
    else:
        curruntpage = int(request.args.get('currentpage'))
        number = request.args.get('number')
        try:
            df = Data.df
            result = [json.loads(df.iloc[i].to_json()) for i in range(len(df))]
            
            numberOfEntries = len(result) // int(number) + 1
            if curruntpage > numberOfEntries:
                return {'code':200,'msg':'超出范围'}
            else:
                result = result[(curruntpage - 1)*int(number) : (curruntpage)*int(number)]
        

            return {'reslut':result,'code':200,'totalpage':numberOfEntries}
        
        except Exception as e:
            return {'code':500,'error':str(e)}

@app.route('/getuser', methods=['GET'])
def getuser():
    id = request.values.get('username')
    cur = conn.cursor()
    cur.execute("SELECT * FROM user where acount = %s", (id))
    data = cur.fetchone()
    i = data
    try:
        result = {
            "id": i[0],
            "username": i[1],
            "password": i[2],
            "email": i[3],
            "img": base64.b64encode(i[-1]).decode('utf-8')
        }
    except:
        result = {
            "id": i[0],
            "username": i[1],
            "password": i[2],
            "email": i[3],
            "img": 'null'
        }

    return {'code': 200, 'result': result}

@app.route('/login', methods=['GET','POST'])
def login():
    acount = request.values.get('username')
    pwd = request.values.get('password')
    cur = conn.cursor()
    sql = "SELECT acount,pwd FROM user where acount = %s"
    cur.execute(sql, (acount))
    data = cur.fetchone()
    if not data:
        return {'code': 202, 'msg': '账号不存在'}
    if pwd != data[1] or data[0] != acount:
        return {'code':201,'msg':'密码或账号错误'}
    else:
        return {'code': 200, 'msg':'登录成功'}
    
@app.route('/register', methods=['POST'])
def register():
    if request.method == "POST":
        username = request.values.get('username')
        password = request.values.get('password')
        e_mail = request.values.get('e_mail')
        cur = conn.cursor()
        sql = "insert into user (acount,pwd,e_mail) values (%s,%s,%s)"
        cur.execute(sql, (username, password, e_mail))
        conn.commit()
        return {'code': 200, "msg":"注册成功"}
    else:
        return {'code': 100,"msg": '错误的请求方法'}


@app.route('/updateUser', methods=['POST'])
def update():
    if request.method == "POST":
        acount = request.values.get('username')
        pwd = request.values.get('password')
        e_mail = request.values.get('email')
        id = request.values.get('id')
        cur = conn.cursor()
        sql = "update user set acount = %s,pwd = %s,e_mail = %s where id = %s "
        cur.execute(sql, (acount, pwd, e_mail,id))
        conn.commit()
        return {'code': 200, "title": "更改信息成功"}
    else:
        return {'code':100,"msg":'错误的请求方法'}

@app.route('/upload', methods=['POST'])
def upload():
    try:
        file = request.files['file']
        id = request.values.get('username')
        cur = conn.cursor()
        sql = "update user set icon = %s where acount = %s"
        cur.execute(sql, (file.read(),id))
        conn.commit()
        return {'code': 200, "msg": "上传成功"}
    except Exception as e:
        return {'code': 500, "msg": str(e)}




if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080) 
 